from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm
from server.database import db_manager
from server.util import check_password, random_str
from server.user_data import server_user_data

router = APIRouter(prefix='/dev', tags=['开发调试'])


@router.post("/token", summary="获取 token 接口")
async def get_token(form_data: OAuth2PasswordRequestForm = Depends()):
    username: str = form_data.username
    password: str = form_data.password
    user = await db_manager.fetch_one("SELECT id,password FROM user WHERE username = :username AND status=1", {"username": username})
    if user is None:
        return {"msg": "登陆失败，用户名与密码不匹配"}
    if not check_password(password, user["password"]):
        return {"msg": "登陆失败，用户名与密码不匹配"}
    token = random_str()
    server_user_data.add_user(token, {"id": user["id"], "username": username})
    # Authorization: bearer header.payload.sign
    return {"access_token": token, "token_type": "bearer"}
